<template>
  <v-page :loading="!trialList" background="#f5f6fa" footer-background="white">
    <template #header>
      <v-navbar title="订单确认页" />
    </template>
    <template #default>
      <view class="order-confirm-block" style="margin-top: 24rpx">
        <view class="address-item" @click="userStore.getAddress">
          <template v-if="userAddress">
            <v-icon
              size="44rpx"
              src="@/static/icons/product-select-address.svg"
            />
            <view class="address-content">
              <view class="address-main">
                {{ userAddress.detailInfo }}
              </view>
              <view class="address-sub">
                <text v-if="userAddress.userName">
                  {{ userAddress.userName }}
                </text>
                <text v-if="userAddress.telNumber">
                  {{ userAddress.telNumber }}
                </text>
              </view>
            </view>
          </template>
          <template v-else>
            <!-- #ifdef MP-ALIPAY -->
            <v-icon size="44rpx" src="@/static/images/alipay-icon.png" />
            <view class="alipay-holder">
              支付宝地址导入
            </view>
            <!-- #endif -->
          </template>
          <wd-icon name="arrow-right" size="24rpx" color="#999999" />
        </view>
      </view>
      <order-confirm-merchant
        v-for="merchant in cartList"
        :key="merchant.merchant_id"
        :merchant="merchant"
        :remark="getRemark(merchant.merchant_id)"
        :shipping-fee="getShippingFee(merchant.merchant_id)"
        @show-remark="showRemarkPopup(merchant)"
      />
    </template>
    <template #footer>
      <view class="page-footer">
        <view class="count-pad">
          <view class="main-text">
            <view class="label">
              合计:
            </view>
            <v-price :price="totalPrice" size="40rpx" />
          </view>
          <view v-if="subText" class="sub-text">
            {{ subText }}
          </view>
        </view>
        <v-button
          type="primary"
          :custom-style="{ height: '80rpx', width: '210rpx' }"
          @click="submitOrderHandle"
        >
          提交订单
        </v-button>
      </view>
    </template>
    <template #popup>
      <m-textarea-popup
        v-model="editingRemark"
        v-model:show="isShowRemarkPopup"
        title="订单备注"
        edit
        @submit="sumitRemarkHandle"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import OrderConfirmMerchant from './modules/order-confirm-merchant.vue';
import usePayment from '@/composables/use-payment';

const { payOrder, cancelMergeOrder } = usePayment();

const userStore = $store.user();
const userAddress = computed(() => userStore.userAddress);

const remarkMap = ref<Map<string, string>>(new Map());
const updateRemark = (merchantId: string, remark: string) => {
  remarkMap.value.set(merchantId, remark);
};
const getRemark = (merchantId: string) => {
  return remarkMap.value.get(merchantId) || '';
};
const isShowRemarkPopup = ref(false);
const editingMerchantId = ref('');
const editingRemark = ref('');
const showRemarkPopup = (merchant: OrderMerchantVO) => {
  editingMerchantId.value = merchant.merchant_id;
  editingRemark.value = getRemark(merchant.merchant_id);
  isShowRemarkPopup.value = true;
};
const sumitRemarkHandle = () => {
  updateRemark(editingMerchantId.value, editingRemark.value);
  isShowRemarkPopup.value = false;
};

const type = ref<'order' | 'cart'>('order');
const cartList = ref<OrderMerchantVO[]>();
const trialList = ref<OrderMerchantVO[]>();
const updateTrialList = async () => {
  const allProduct =
    cartList.value?.flatMap((merchant) => merchant.detail_list) ?? [];
  const response = await $api.postOrderSubmitTrial({
    order_req: allProduct.map((item) => ({
      sku_id: item.sku_id,
      quantity: item.quantity,
      discount_type: 'NONE',
      landing_page_id: item.spu_id,
      activity_id: item.activity_id,
      activity_type: item.activity_type
    })),
    recipient_info: userStore.getRecipientInfo()
  });
  switch (response.__error) {
    case undefined:
      trialList.value = response.data.list;
      break;
  }
};
const getShippingFee = (merchantId: string) => {
  const merchant = trialList.value?.find(
    (item) => item.merchant_id === merchantId
  );
  return merchant?.shipping_fee ?? -1;
};

const loading = ref(true);
onLoad(async (query) => {
  type.value = query?.type as 'order' | 'cart';
  const pageStore = $store.page();
  loading.value = true;
  if (type.value === 'cart') {
    // 购物车进入，获取购物车列表
    const parameters = pageStore.parameters as {
      list: OrderMerchantVO[];
    };
    cartList.value = parameters.list;
    if (!cartList.value) return uni.navigateBack();
  } else {
    // 商品详情进入，拿store里的数据
    const parameters = pageStore.parameters as {
      list: OrderMerchantVO[];
      remark: string;
    };
    cartList.value = parameters.list;
    if (!cartList.value) return uni.navigateBack();
    // 这里带出了直接下单时的备注
    for (const merchant of cartList.value) {
      updateRemark(merchant.merchant_id, parameters.remark);
    }
  }
  loading.value = false;
  watch(
    () => userStore.userAddress?._t,
    (val) => {
      if (val) updateTrialList();
    },
    { immediate: true }
  );
});

const totalPrice = computed(() => {
  if (!trialList.value) return 0;
  return trialList.value.reduce((acc, cur) => {
    return (
      acc +
      (cur.shipping_fee ?? 0) +
      cur.detail_list.reduce((acc, cur) => {
        return acc + cur.quantity * (cur.sell_price ?? 0);
      }, 0)
    );
  }, 0);
});

const subText = computed(() => {
  if (!trialList.value) return '';
  const shippingFee = trialList.value.reduce(
    (acc, cur) => acc + (cur.shipping_fee ?? 0),
    0
  );
  if (shippingFee) {
    return `含运费￥${shippingFee}`;
  }
  return '';
});

/** 实际的购物车列表 */
const refreshCurrentCartList = async () => {
  const response = await $api.getCartList({
    all: true
  });
  switch (response.__error) {
    case undefined:
      return response.data.list.flatMap((item) => item.cart_list);
  }
};
const verify = () => {
  if (!userAddress.value) {
    uni.showToast({ title: '请选择收货地址', icon: 'none' });
    return false;
  }
  return true;
};
const submitOrderHandle = async () => {
  const result = verify();
  if (!result) return;
  let currentCartList: CartVO[] | undefined = [];
  if (type.value === 'cart') {
    currentCartList = await refreshCurrentCartList();
  }
  uni.showLoading({ mask: true });
  const response = await $api.postOrderSubmitUpsert(
    trialList.value?.map((merchant) => {
      const detailList =
        merchant.detail_list.map((item) => ({
          ...item,
          landing_page_id: ''
        })) ?? [];
      const cartList =
        currentCartList?.filter((item) =>
          detailList.some((detail) => detail.sku_id === item.sku_id)
        ) ?? [];
      return {
        uid: merchant.uid,
        merchant_id: merchant.merchant_id,
        recipient_info: userStore.getRecipientInfo(),
        detail_list: detailList,
        cart_list: cartList.map((item) => ({ cart_id: item.id })),
        customer_remark: getRemark(merchant.merchant_id),
        landing_page_id: ''
      };
    }) ?? []
  );
  uni.hideLoading();
  switch (response.__error) {
    case undefined: {
      // #ifdef MP-ALIPAY
      if (response.data.pay_product === 'MERGE_PAY') {
        const tradeNo = response.data.merge_no ?? response.data.trade_no;
        const result = await payOrder(tradeNo, { bizType: 'merge_order' });
        if (!result) {
          uni.showLoading({ mask: true });
          await cancelMergeOrder(
            response.data.out_merge_no,
            response.data.order_detail_result,
            userStore.getRecipientInfo(),
            trialList.value ?? [],
            remarkMap.value
          );
          uni.hideLoading();
        }
      } else {
        await payOrder(response.data.trade_no);
      }
      // #endif
      // #ifdef MP-WEIXIN
      await payOrder({
        timeStamp: response.data.pay_we_chat?.timeStamp,
        nonceStr: response.data.pay_we_chat?.nonceStr,
        package: response.data.pay_we_chat?.packageVal,
        signType: response.data.pay_we_chat?.signType,
        paySign: response.data.pay_we_chat?.paySign
      });
      // #endif
      uni.redirectTo({ url: '/pages/order/order-page' });
      break;
    }
  }
};
</script>

<style lang="scss" scoped>
.order-confirm-block {
  margin: 0 24rpx 24rpx;
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 12rpx;
  .address-item {
    display: flex;
    align-items: center;
    gap: 24rpx;
    .address-content {
      flex: 1;
      min-width: 0;
      .address-main {
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        margin-bottom: 8rpx;
      }
      .address-sub {
        color: #999999;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        display: inline-flex;
        gap: 0 8rpx;
      }
    }
    .alipay-holder {
      color: #007afe;
      flex: 1;
      min-width: 0;
    }
    .weixin-holder {
      color: #07c160;
    }
  }
}
.page-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
  .count-pad {
    display: flex;
    flex-direction: column;
    gap: 3rpx;
    .main-text {
      display: flex;
      align-items: baseline;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
    }
    .sub-text {
      font-size: 22rpx;
      color: #999999;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
    }
  }
}
</style>
